package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.util.RequirePermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    //处理查询所有部门的请求
    @RequestMapping("/list")
    //为了防备获取权限的名字,可以把逻辑改为或(其中一个有就可以访问)
    @RequiresPermissions(value = {"department:list","部门页面"},logical = Logical.OR)
    public String list(Model model,QueryObject qo){
        //查询所有部门数据,存在模型
        //List<Department> departments = departmentService.listAll();
        //处理分页查询部门的请求
        //model.addAttribute("departments",departments);

        //Subject subject = SecurityUtils.getSubject();
        //需要判断角色或者权限的时候,shiro会自动调用realm的doGetAuthorizationInfo获取用户的数据,来进行对比


        PageInfo<Department> pageInfo = departmentService.query(qo);
        model.addAttribute("pageResult",pageInfo);
        return "department/list";  //  /WEB-INF/views/department/list.ftl
    }

    //处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    //@RequiresPermissions("depatrment:delete")
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                departmentService.delete(id);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }

    /*//处理去新增请求
    @RequestMapping("/input")
    public String input(Long id,Model model){

        //如果传id就传去修改
        if (id!=null){
            model.addAttribute("department",departmentService.get(id));
        }
        return "department/input";
    }*/

    //处理新增请求
    @RequestMapping("/saveOrUpdate")
    //@RequirePermission(name = "部门保存或更新",expression = "department:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Department department){
        try {

            if (department.getId()!=null){
                //修改
                departmentService.update(department);
            }else {
                //新增
                departmentService.save(department);
            }
            return new JsonResult();
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败");
        }

    }

}
